package cn.jekun.web.shop.action;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.RsRole;
import cn.jekun.component.core.service.gen.RsRoleService;
import cn.jekun.web.shop.bean.Role;
import cn.jekun.web.shop.service.RoleService;

public class RoleAction extends ShopBaseAction  {

	@Resource(name=RoleService.BEAN_NAME)
	RoleService roleService;
	
	@Resource(name=RsRoleService.BEAN_NAME)
	RsRoleService rsRoleService;
	
	private RsRole role;
	private List<String> checkBoxAuth;
	private List<String> roleAuthId;
	
	
	
	public List<String> getCheckBoxAuth() {
		return checkBoxAuth;
	}

	public void setCheckBoxAuth(List<String> checkBoxAuth) {
		this.checkBoxAuth = checkBoxAuth;
	}

	public List<String> getRoleAuthId() {
		return roleAuthId;
	}

	public void setRoleAuthId(List<String> roleAuthId) {
		this.roleAuthId = roleAuthId;
	}

	public RsRole getRole() {
		return role;
	}

	public void setRole(RsRole role) {
		this.role = role;
	}

	/**
	 * 列表
	 * @return
	 */
	public String list() {
		
		String tempRoleName = request.getParameter("roleName");
		String userId=this.getSessionUser().getUserId();
		
		JSONObject jsonObject=new JSONObject();
		
		try{
			
			this.resultList = roleService.list(tempRoleName,userId, page);
			
			JSONArray jsonArray = new JSONArray();
			
			HashMap<String, Object> hashMap;
			
			for(int i=0;i<this.resultList.size();i++){
				
				RsRole tempRsRole=(RsRole) resultList.get(i);
				
				hashMap=new HashMap<String, Object>();
				
				hashMap.put(RsRole.COL_ROLE_ID, tempRsRole.getRoleId());
				
				hashMap.put(RsRole.COL_ROLE_NAME, tempRsRole.getRoleName());
				
				jsonArray.add(hashMap);
				
			}
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

			jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());
			
			jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());
			
			jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
			
			jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());
			
			jsonObject.put("roleListData", jsonArray);
			
			
		}catch(Exception e){
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
			
			e.printStackTrace();
		}
		
		return this.writeJson(jsonObject);
		
	}
	
	/**
	 * 增加
	 * @return
	 */
	public String add(){
		
		JSONObject jsonObject=new JSONObject();
		
		try {
			
			boolean exists = this.roleService.exists(role.getRoleName(),this.getSessionUser().getShopId());
			if(exists){

				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);

				jsonObject.put(ErrorMsg.KEY_MESSAGE,"新增角色失败，角色名称已存在！，角色名称:"+role.getRoleName());

				this.logService.addAdminAuditLog("", "新增角色失败，角色名称已存在！，角色名称:"+role.getRoleName());

			}else{
				formMap.remove(SqlUtis.WHERE_SQL);
			}
			
			formMap.put("rsRole", role);
			Object  obj=this.rsRoleService.insert(formMap);
			formMap.remove(SqlUtis.WHERE_SQL);
			//end保存到数据库
			coreAuthService.clearCache();//清空缓存
			this.logService.addAdminAuditLog("", "新增角色成功");//记录操作日志
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
							
			
			
		} catch (Exception e) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
			
			e.printStackTrace();
		}
		
		return this.writeJson(jsonObject);
		
	}
	
	/**
	 * 转到编辑
	 * @return
	 */
	public String toEdit(){
		
		
		JSONObject jsonObject=new JSONObject();
		
		try {
			
			this.role = this.roleService.getRole(this.role.getRoleId());
			
			jsonObject.put(RsRole.COL_ROLE_ID,role.getRoleId());
			jsonObject.put(RsRole.COL_ROLE_NAME,role.getRoleName());
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
			
		} catch (Exception e) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
			
			e.printStackTrace();
		}
		
		
		return this.writeJson(jsonObject);
		
	}
	/**
	 * 编辑
	 * @return
	 */
	public String edit(){
		JSONObject jsonObject=new JSONObject();
		
		try {
			
			formMap.put(RsRole.COL_ROLE_ID, this.role.getRoleId());
			SqlUtis.prepareSql(formMap, ""
				,SqlUtis.getSQLRequired(formMap,"a."+RsRole.COL_ROLE_ID,Types.VARCHAR,SqlUtis.EQ)
			);
			RsRole dbvalue = this.roleService.getRole(this.role.getRoleId());
			if(dbvalue == null){
				throw new BusinessException("记录已经被删除，更新失败!");
			}else{
				formMap.remove(SqlUtis.WHERE_SQL);
			}
			//更新数据库
			SqlUtis.prepareSql(formMap,""
				,SqlUtis.getSQLRequired(formMap,"a."+RsRole.COL_ROLE_ID,Types.VARCHAR,SqlUtis.EQ)
			);
			formMap.put("rsRole", role);
//			this.rsRoleService.update(formMap);
			this.roleService.updateRole(role);
			formMap.remove(SqlUtis.WHERE_SQL);
			//end 更新数据库
			coreAuthService.clearCache();//清空缓存

			this.logService.addAdminAuditLog("", "修改角色成功:"+role.getRoleId());//记录操作日志
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

		} catch (Exception e) {
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
			
			e.printStackTrace();
		}
		
		
		return this.writeJson(jsonObject);
		
		
	}
	
	
	/**
	 * 查询该系统的权限
	 * @return
	 */
	public String querySystemAuth(){
		
		JSONObject jsonObject=new JSONObject();
		
		try {
			String systemId=Constants.RS_SYSTEM.SHOP;
			
			String roleId=request.getParameter("roleId");

			List<HashMap> authList = this.roleService.getAuthList(this.getSessionUser().getUserId(),roleId, systemId);
			
			JSONArray jsonArray = new JSONArray();
			
			HashMap<String, Object> hashMap;
			
			for(int i=0;i<authList.size();i++){
				
				if(authList.get(i).get("PARENT_ID")==null){
					
						hashMap=new HashMap<String, Object>();
						
						hashMap.put("AUTH_NAME", authList.get(i).get("AUTH_NAME")==null?"":authList.get(i).get("AUTH_NAME"));
//						hashMap.put("ROLE_ID", authList.get(i).get("ROLE_ID")==null?"":authList.get(i).get("ROLE_ID"));
						hashMap.put("AUTH_ID", authList.get(i).get("AUTH_ID")==null?"":authList.get(i).get("AUTH_ID"));
						hashMap.put("MEMO", authList.get(i).get("MEMO")==null?"":authList.get(i).get("MEMO"));
						hashMap.put("URL", authList.get(i).get("URL")==null?"":authList.get(i).get("URL"));
						hashMap.put("ROLE_AUTH_ID", authList.get(i).get("ROLE_AUTH_ID")==null?"":authList.get(i).get("ROLE_AUTH_ID").toString());
						JSONArray json=new JSONArray();
						
						HashMap<String, Object> map;
						
						for(int j=0;j<authList.size();j++){
							//查询父项中的子项
							if(authList.get(i).get("AUTH_ID").equals(authList.get(j).get("PARENT_ID"))){
								
								//查询功能权限
								HashMap<String, Object> smap;
								JSONArray sjson=new JSONArray();
								for(int k=0;k<authList.size();k++){
									
									if(authList.get(j).get("AUTH_ID").equals(authList.get(k).get("PARENT_ID"))){
										
										 smap=new HashMap<String, Object>();
										 smap.put("AUTH_ID", authList.get(k).get("AUTH_ID")==null?"":authList.get(k).get("AUTH_ID"));
										 smap.put("AUTH_NAME", authList.get(k).get("AUTH_NAME")==null?"":authList.get(k).get("AUTH_NAME"));
//										 smap.put("ROLE_ID", authList.get(k).get("ROLE_ID")==null?"":authList.get(k).get("ROLE_ID"));
										 smap.put("PARENT_ID", authList.get(k).get("PARENT_ID")==null?"":authList.get(k).get("PARENT_ID"));
										 smap.put("URL", authList.get(k).get("URL")==null?"":authList.get(k).get("URL"));
										 smap.put("ROLE_AUTH_ID", authList.get(k).get("ROLE_AUTH_ID")==null?"":authList.get(k).get("ROLE_AUTH_ID").toString());
										 smap.put("MEMO", authList.get(k).get("MEMO")==null?"":authList.get(k).get("MEMO").toString());
										 sjson.add(smap);
									}
								}
								
								map=new HashMap<String, Object>();
								map.put("AUTH_ID", authList.get(j).get("AUTH_ID")==null?"":authList.get(j).get("AUTH_ID"));
								map.put("AUTH_NAME", authList.get(j).get("AUTH_NAME")==null?"":authList.get(j).get("AUTH_NAME"));
//								map.put("ROLE_ID", authList.get(j).get("ROLE_ID")==null?"":authList.get(j).get("ROLE_ID"));
								map.put("PARENT_ID", authList.get(j).get("PARENT_ID")==null?"":authList.get(j).get("PARENT_ID"));
								map.put("URL", authList.get(j).get("URL")==null?"":authList.get(j).get("URL"));
								map.put("ROLE_AUTH_ID", authList.get(j).get("ROLE_AUTH_ID")==null?"":authList.get(j).get("ROLE_AUTH_ID").toString());
								map.put("MEMO", authList.get(j).get("MEMO")==null?"":authList.get(j).get("MEMO").toString());
								map.put("FUNCTION_MUNU",sjson);
								
								json.add(map);
								
								
							}
							
						}
						
						hashMap.put("CHILD_MUNU",json);

						jsonArray.add(hashMap);
						
				}
				
			}
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

			jsonObject.put("authRoleListData", jsonArray);
			
			return this.writeJson(jsonObject);

			
		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
		}
		
		return this.writeJson(jsonObject);
	}
	
	/**
	 * 分配权限
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String assignAuth(){
	
	
		JSONObject jsonObject=new JSONObject();
		
		try {
			
			//保存数据
			formMap.put(RsRole.COL_ROLE_ID, this.role.getRoleId());
			
			formMap.put("checkBoxAuth", checkBoxAuth);
			
			formMap.put("roleAuthIdList",roleAuthId);
			
			this.roleService.assignAuth(this.role.getRoleId(),checkBoxAuth,roleAuthId);
			
			this.coreAuthService.clearCache();
		
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"分配权限成功");

		} catch (Exception e) {
			e.printStackTrace();
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"分配权限失败");
			
		}
		
		return this.writeJson(jsonObject);
	}
	
	/**
	 * 转到分配角色
	 * @author shimh
	 * @return
	 */
	public String toAssignRole(){
		
		JSONObject jsonObject=new JSONObject();
		
		//查询角色权限
		String userId =(String) formMap.get("USER_ID");
		
		List<Role> resultList = this.roleService.getAuthListByUserId(userId,this.getSessionUser().getUserId());
		
		JSONArray jsonArray = new JSONArray();
		
		HashMap<String, Object> hashMap=new HashMap<String, Object>();
		
		for(int i=0;i<resultList.size();i++){
			
		
			hashMap.put(Role.COL_ROLE_ID, resultList.get(i).getRoleId());
			
			hashMap.put(Role.COL_ROLE_NAME, resultList.get(i).getRoleName());
			
			hashMap.put("CHECKED",resultList.get(i).getChecked());
			
	
			jsonArray.add(hashMap);
			
		}
		
		jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
		
		jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

		jsonObject.put("roleListData", jsonArray);
		
		return this.writeJson(jsonObject);

	}
	
	/**
	 * 分配角色
	 * @author shimh
	 * @return
	 */
	public String assignRole(){
		JSONObject jsonObject=new JSONObject();
		try{
			String tempUserId = (String)formMap.get("USER_ID");
			String tempRoleId = (String)formMap.get("ROLE_ID");
			
//			this.roleService.assignRole(formMap);
			this.roleService.assignRole(tempUserId, tempRoleId);
			
			coreAuthService.clearCache();//清空缓存
		
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
			
			
		}catch(Exception e){
			
			jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
			
			jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用失败");
			
		}
		
		return this.writeJson(jsonObject);
	}
}
